package day11.CRUD;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.ResultSet;

public class Demo2 {
    @Test
    public void add(){
        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs = null;

        try{
            conn = JdbcUtils.getConnection();
            String sql = "insert into testblob(image) values(?)";
            st = (PreparedStatement) conn.prepareStatement(sql);
            String path = Demo2.class.getClassLoader().getResource("01.jpg").getPath();
            st.setBinaryStream(1, new FileInputStream(path), (int) new File(path).length());
            int num = st.executeUpdate();
            if(num>0){
                System.out.println("插入成功！！");
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally{
            JdbcUtils.release(conn, st, rs);
        }
    }

    @Test
    public void read(){
        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs = null;

        try{
            conn = JdbcUtils.getConnection();
            String sql = "select image from testblob where id=?";
            st = (PreparedStatement) conn.prepareStatement(sql);
            st.setInt(1, 1);
            rs = st.executeQuery();
            if(rs.next()){
                InputStream in = rs.getBinaryStream("image");
                int len = 0;
                byte buffer[] = new byte[1024];

                FileOutputStream out = new FileOutputStream("c:\\1.jpg");
                while((len=in.read(buffer))>0){
                    out.write(buffer,0, len);
                }
                in.close();
                out.close();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally{
            JdbcUtils.release(conn, st, rs);
        }
    }
}